<template>
  <Row>
    <Col span="5">
      <Card>
        <template #title>
          <Icon type="md-clock" size="25" />
          待办事项
        </template>
        <template #extra>
          <Button type="text" icon="md-refresh" @click="getNum">刷新</Button>
        </template>
        <Collapse v-model="value">
          <Panel name="1">
            <Icon type="md-close" size="20" />上传失败待处理
            <template #content>清单数：{{ thingsParams.qds }}</template>
          </Panel>
          <Panel name="2">
            <Icon type="ios-briefcase" size="20" />待审核清单
            <template #content>
              <Space direction="vertical">
                <Row>
                  <Col span="18"
                    >全部待审核清单：{{ thingsParams.dsh ? thingsParams.dsh + '条' : '' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.dsh">
                    <Button size="small" type="primary" icon="md-build" @click="goList">
                      去处理
                    </Button>
                  </Col>
                </Row>
                <Row>
                  <Col span="18"
                    >临近上传时间清单：{{ thingsParams.ljsc ? thingsParams.ljsc + '条' : '0' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.ljsc"
                    ><Button size="small" type="primary" icon="md-build" @click="goList"
                      >去处理</Button
                    >
                  </Col>
                </Row>
                <Row>
                  <Col span="18"
                    >超出上传时间清单：{{ thingsParams.ccsc ? thingsParams.ccsc + '条' : '0' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.ccsc"
                    ><Button size="small" type="primary" icon="md-build" @click="goList"
                      >去处理</Button
                    >
                  </Col>
                </Row>
              </Space>
            </template>
          </Panel>
          <Panel name="3">
            <Icon type="md-alert" size="20" />系统审核异常清单
            <template #content>
              <Space direction="vertical">
                <Row>
                  <Col :span="thingsParams.shyc ? 18 : 24"
                    >系统审核异常清单：{{ thingsParams.shyc ? thingsParams.shyc + '条' : '0' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.shyc"
                    ><Button size="small" type="primary" icon="md-build" @click="goList"
                      >去处理</Button
                    >
                  </Col>
                </Row>
                <Row>
                  <Col :span="thingsParams.sshm ? 18 : 24"
                    >主要手术灰码：{{ thingsParams.sshm ? thingsParams.sshm + '条' : '0' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.sshm"
                    ><Button size="small" type="primary" icon="md-build" @click="goList"
                      >去处理</Button
                    >
                  </Col>
                </Row>
                <Row>
                  <Col :span="thingsParams.bpp ? 18 : 24"
                    >诊断与手术不匹配：{{ thingsParams.bpp ? thingsParams.bpp + '条' : '0' }}
                  </Col>
                  <Col span="4" v-if="thingsParams.bpp"
                    ><Button size="small" type="primary" icon="md-build" @click="goList"
                      >去处理</Button
                    >
                  </Col>
                </Row>
              </Space>
            </template>
          </Panel>
          <Panel name="4">
            <Icon type="ios-folder" size="20" />其他待处理事项
            <template #content></template>
          </Panel>
        </Collapse>
      </Card>
    </Col>
    <Col span="19" style="padding-left: 20px">
      <Form :model="form" ref="formRef">
        <Row>
          <Col span="5">
            <FormItem label="科室" prop="categoryID" :label-width="50">
              <Select filterable v-model="form.categoryID">
                <Option v-for="item in ksEnum" :value="item.label" :key="item.value">
                  {{ item.value }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="主诊医师" prop="dcName" :label-width="80">
              <Input v-model="form.dcName" placeholder="请输入"> </Input>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="医保类型" prop="insureType" :label-width="80">
              <Select filterable v-model="form.insureType">
                <Option v-for="item in ybEnum" :value="item.label" :key="item.value">
                  {{ item.value }}
                </Option>
              </Select>
            </FormItem>
          </Col>
          <Col span="5">
            <FormItem label="出院时间" prop="outTime" :label-width="80">
              <DatePicker
                v-model="form.outTime"
                format="yyyy-MM-dd"
                type="daterange"
                @on-change="form.outTime = $event"
                placeholder="请选择"
              />
            </FormItem>
          </Col>
          <Col span="4">
            <Space style="display: flex; justify-content: flex-end">
              <Button type="primary" icon="md-search" @click="goSearch">查询</Button>
              <Button type="dashed" icon="md-refresh" @click="reset">重置</Button>
            </Space>
          </Col>
        </Row>
        <Divider orientation="left"> <Icon type="md-cloud-upload" size="20" />上传情况 </Divider>
        <Row justify="space-around" flex="middle">
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="magenta">未上传数</Tag>
                  <CountUp :end="updateParams.wsc" :duration="2" ref="count" v-font="24" />
                  <Text italic>近30天</Text>&nbsp;
                  <Trend flag="up" text-color> 12.5%</Trend>
                </Space>
              </div>
            </Card>
          </Col>
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="success"> 上传成功数</Tag>
                  <CountUp :end="updateParams.sccg" :duration="2" ref="count" v-font="24" />
                  <Text italic>近30天</Text>&nbsp;
                  <Trend flag="up" text-color> 12.5%</Trend>
                </Space>
              </div>
            </Card>
          </Col>
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="volcano">上传失败数</Tag>
                  <CountUp :end="updateParams.scsb" :duration="2" ref="count" v-font="24" />
                  <Text italic>近30天</Text>&nbsp;
                  <Trend flag="up" text-color> 12.5%</Trend>
                </Space>
              </div>
            </Card>
          </Col>
        </Row>
        <!-- <Row>
          <Col span="24">
            <div style="width: 100%; height: 350px; padding-top: 20px" id="line1"></div>
          </Col>
        </Row> -->

        <Row>
          <Col span="24">
            <div style="width: 100%; height: 350px; padding-top: 20px" id="line2"></div>
          </Col>
        </Row>
        <Divider orientation="left">
          <Icon type="md-checkmark-circle-outline" size="20" />审核情况
        </Divider>

        <Row justify="space-around" flex="middle">
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="magenta">总病例数</Tag>
                  <CountUp :end="updateParams.zbls" :duration="2" ref="count" v-font="24" />
                </Space>
              </div>
            </Card>
          </Col>
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="volcano"> 待审核</Tag>
                  <CountUp :end="updateParams.dsh" :duration="2" ref="count" v-font="24" />
                </Space>
              </div>
            </Card>
          </Col>
          <Col span="4">
            <Card>
              <div style="text-align: center">
                <Space direction="vertical">
                  <Tag size="large" color="success">已审核</Tag>
                  <CountUp :end="updateParams.ysh" :duration="2" ref="count" v-font="24" />
                </Space>
              </div>
            </Card>
          </Col>
        </Row>
        <Row>
          <Col span="12">
            <div style="width: 100%; height: 350px; padding-top: 20px" id="pie"></div>
          </Col>
          <Col span="12">
            <div style="width: 100%; height: 350px; padding-top: 20px" id="bar"></div>
          </Col>
        </Row>
      </Form>
    </Col>
  </Row>
</template>
<script setup>
import { onActivated, reactive, ref, nextTick, onUnmounted } from 'vue'

import http from '@/util/http1'
import { useRouter } from 'vue-router'
const router = useRouter()
import { ybEnum, ksEnum } from '../list/components/Enum.js'
import * as echarts from 'echarts'
import { onMounted } from 'vue'

const thingsParams = reactive({
  qds: 0,
  dsh: 0,
  ljsc: 0,
  ccsc: 0,
  shyc: 0,
  sshm: 0,
  bpp: 0,
})

let form = ref({
  categoryID: '',
  dcName: '',
  insureType: '',
  startDate: '',
  endDate: '',
  outTime: [],
})

const value = ['1', '2', '3', '4', '5']

const lineList = ref({
  legend: [],
  xAxis: [],
  series: [],
})

let initLine1 = () => {
  var line1 = document.getElementById('line1')
  var lineChart1 = echarts.init(line1)
  var option1 = {
    title: {
      text: '患者总数、已提交病案数、已生成清单数趋势图',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      bottom: 0,
      data: ['患者总数', '已提交病案数', '已生成清单数'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['2024-9', '2024-10', '2024-11', '2024-12', '2025-1', '2025-2', '2025-3'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '患者总数',
        type: 'line',
        stack: 'Total',
        data: [120, 132, 101, 120, 132, 101, 200],
      },
      {
        name: '已提交病案数',
        type: 'line',
        stack: 'Total',
        data: [220, 182, 191, 120, 132, 101, 300],
      },
      {
        name: '已生成清单数',
        type: 'line',
        stack: 'Total',
        data: [150, 232, 201, 120, 132, 101, 400],
      },
    ],
  }
  lineChart1.setOption(option1)
}

let lineChart2 = null

const initLine2 = () => {
  if (!lineChart2) {
    const line2 = document.getElementById('line2')
    lineChart2 = echarts.init(line2)
  }

  const option2 = {
    title: {
      text: '上传情况趋势图',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      bottom: 0,
      data: lineList.value.legend || [],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '12%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: lineList.value.xAxis || [],
    },
    yAxis: {
      type: 'value',
    },
    series: lineList.value.series || [],
  }

  lineChart2.setOption(option2)
}

let initPie = () => {
  if (!lineChart2) {
    var pie = document.getElementById('pie')
    var pieChart = echarts.init(pie)
  }
  var pie = document.getElementById('pie')
  var pieChart = echarts.init(pie)

  const yshValue = Number(updateParams.value.ysh) || 0
  const wshValue = Number(updateParams.value.wsh) || 0

  const pieData =
    yshValue === 0 && wshValue === 0
      ? [
          { value: 0, name: '已审核' },
          { value: 0, name: '未审核' },
        ]
      : [
          { value: yshValue, name: '已审核' },
          { value: wshValue, name: '未审核' },
        ]

  var option = {
    title: {
      text: '审核数占比',
      left: 'center',
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['已审核', '未审核'],
    },
    series: [
      {
        name: '审核数',
        type: 'pie',
        radius: '50%',
        data: pieData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
        label: {
          show: true,
          formatter: '{b}\n{c}',
          position: 'inside',
        },
      },
    ],
  }

  pieChart.setOption(option)
}

const barList = ref({
  yAxis: [],
  series: [],
})

let initBar = () => {
  var bar = document.getElementById('bar')
  var barChart = echarts.init(bar)
  var option = {
    title: {
      text: '审核异常排名',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      top: 80,
      bottom: 30,
      left: '20%', // 增加左侧空间
      right: '4%',
    },
    xAxis: {
      type: 'value',
      position: 'top',
      splitLine: {
        lineStyle: {
          type: 'dashed',
        },
      },
    },
    yAxis: {
      type: 'category',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: { show: false },
      data: barList.value.yAxis || [],
      axisLabel: {
        formatter: function (value) {
          const length = 20
          const rows = Math.ceil(value.length / length)
          const newValue = []
          for (let i = 0; i < rows; i++) {
            newValue.push(value.slice(i * length, (i + 1) * length))
          }
          return newValue.join('\n')
        },
        interval: 0,
        lineHeight: 14,
        padding: [3, 0, 3, 0],
        width: 120,
        overflow: 'break',
      },
    },
    series:
      barList.value.series?.map((item) => ({
        ...item,
        barWidth: 20,
        barGap: '100%',
        itemStyle: {
          borderRadius: [0, 4, 4, 0],
        },
      })) || [],
  }
  barChart.setOption(option)
}
const updateParams = ref({
  total: 0,
  wsc: 0,
  sccg: 0,
  scsb: 0,
  zbls: 0,
  dsh: 0,
  ysh: 0,
})
const getNum = () => {
  http.get('/Settlement/List/LeftData').then((response) => {
    Object.assign(thingsParams, response.data)
  })
}

const formRef = ref(null)

const goSearch = async () => {
  const params = {
    ...form.value,
    startDate: form.value.outTime?.[0] || '',
    endDate: form.value.outTime?.[1] || '',
  }

  try {
    const response = await http.post('/Settlement/List/RightData', params)
    Object.assign(updateParams, response.data)

    lineList.value = response.data.line || { legend: [], xAxis: [], series: [] }
    barList.value = response.data.bar || { yAxis: [], series: [] }

    nextTick(() => {
      initLine2()
      initBar()
    })
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}

const reset = () => {
  formRef.value.resetFields()
}

const goList = () => {
  router.push({ path: '/Settlement/newList/PageList' })
}
onMounted(() => {
  // initLine1()
  initLine2()
  initPie()
  initBar()
  window.addEventListener('resize', () => {
    lineChart2?.resize()
  })
})
onActivated(() => {
  getNum()
  goSearch()
})
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    lineChart2?.resize()
  })
  lineChart2?.dispose()
})
</script>
